package com.fafica.controlador;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.fafica.dominio.Area;
import com.fafica.entidades.Inscrito;

//import javazoom.upload.MultipartFormDataRequest;
//import javazoom.upload.UploadBean;
//import javazoom.upload.UploadException;
//import javazoom.upload.UploadFile;

/**
 * Servlet implementation class ServletUpload
 */
@WebServlet("/artigo")
public class ServletUpload extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletUpload() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Inscrito inscrito = (Inscrito) session.getAttribute("inscrito");
		String retorno = "resumo_inscricao.jsp?msg=arquivo_sucesso";
        PrintWriter out = response.getWriter();
		
		String diretorio = "/var/www/upload_artigos/";
		
		DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
		
		ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
		
		try {
			List itens = servletFileUpload.parseRequest(request);
			Iterator iter = itens.iterator();
			
			while(iter.hasNext()){	
				FileItem item = (FileItem)iter.next();
				
				if(!item.isFormField()){
					File file = new File(diretorio, inscrito.getNome() + " - " + item.getName());
					item.write(file);
				}
			}
			
			out.println("Salvo com sucesso");
			retorno = "resumo_inscricao.jsp?msg=arquivo_sucesso";
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			out.println("Erro");
			retorno = "resumo_inscricao.jsp?msg=arquivo_nao_enviado";
			e.printStackTrace();
		} catch (Exception e) {
			out.println("Erro");
			retorno = "resumo_inscricao.jsp?msg=arquivo_nao_enviado";
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		response.sendRedirect(retorno);
//		String retorno = "resumo_inscricao.jsp?msg=arquivo_sucesso";
//		HttpSession session = request.getSession();
//		Inscrito inscrito = (Inscrito) session.getAttribute("inscrito");
//		String caminho = getServletContext().getRealPath("upload_artigos");
//		try{
//			
//			
//			if (MultipartFormDataRequest.isMultipartFormData(request)){
//				MultipartFormDataRequest mrequest = new MultipartFormDataRequest(request);
//				String area = mrequest.getParameter("area");
//				if(area.equals(Area.EDUCACAO)){
//					caminho += "/educacao";
//				}else if(area.equals(Area.CONTABEIS)){
//					caminho += "/contabeis";
//				}else if(area.equals(Area.TECNOLOGIA)){
//					caminho += "/tecnologia";
//				}else if(area.equals(Area.GESTAO)){
//					caminho += "/gestao";
//				}
//				PrintWriter out = response.getWriter();
//				UploadBean upBean = new UploadBean();
//				upBean.setParser(MultipartFormDataRequest.CFUPARSER);
//				upBean.setFolderstore(caminho);
//				upBean.setParsertmpdir("temp");
//				upBean.setOverwritepolicy("nametimestamp");
//				Hashtable files = mrequest.getFiles();
//				if ( (files != null) && (!files.isEmpty()) ){
//					UploadFile file = (UploadFile) files.get("artigo");
//					String nomeArquivo = String.valueOf(inscrito.getId()) + " " + file.getFileName();
//					file.setFileName(nomeArquivo);
//					upBean.store(mrequest, "artigo");
//					retorno = "resumo_inscricao.jsp?msg=arquivo_sucesso";
//				}else{
//					retorno = "resumo_inscricao.jsp?msg=arquivo_nao_enviado";
//				}
//			}
//		}catch(Exception e){
//			e.printStackTrace();
//		}
//		response.sendRedirect(retorno);
	}

}
